package cn.xuyang520.tyim.sys.config;

import cn.xuyang520.tyim.sys.core.TySysAjaxException;
import cn.xuyang520.tyim.sys.core.TySysAjaxResult;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 统一异常配置
 */
@ControllerAdvice
public class TySysExceptionHandler {

    /**
     * 自定义ajax异常
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = TySysAjaxException.class)
    @ResponseBody
    public TySysAjaxResult jsonErrorHandler(HttpServletRequest req, TySysAjaxException e) throws Exception {
        TySysAjaxResult r = new TySysAjaxResult();
        r.setMsg(e.getMessage());
        r.setSuccess(false);
        return r;
    }

    /**
     * 自定义权限异常
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = AuthorizationException.class)
    public ModelAndView authErrorHandler(HttpServletRequest req, AuthorizationException e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName("403");
        return mav;
    }


    /**
     * 全部异常
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        e.printStackTrace();
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName("500");
        return mav;
    }


}
